// 判断文字方向
function strDir(str) {
    if (str && str.length > 0 && this.isUyghur(str.substr(0, 1))) {
        return 'rtl' // 维吾尔语，设置为右到左的方向
    } else return 'ltr' // 设置为左到右的方向
}

// 是否维吾尔语
function isUyghur(str) {
    var reg = /[\u0600-\u06FF]/
    return reg.test(str)
}

// 是否中文
function isChinese(str) {
    var reg = /^[\u4E00-\u9FA5|。|，|？|！|“|”|：|；|、|《|》|—|（|）|\ |\n|·|0-9]+$/
    return reg.test(str)
}


//打开App
function gotoAppPermissionSetting() {
    var isIos
    // #ifdef APP-PLUS
    isIos = plus.os.name == 'iOS'
    // #endif
    if (isIos) {
        var UIApplication = plus.ios.import('UIApplication')
        var application2 = UIApplication.sharedApplication()
        var NSURL2 = plus.ios.import('NSURL')
        // var setting2 = NSURL2.URLWithString("prefs:root=LOCATION_SERVICES");
        var setting2 = NSURL2.URLWithString('app-settings:')
        application2.openURL(setting2)

        plus.ios.deleteObject(setting2)
        plus.ios.deleteObject(NSURL2)
        plus.ios.deleteObject(application2)
    } else {
        // console.log(plus.device.vendor);
        var Intent = plus.android.importClass('android.content.Intent')
        var Settings = plus.android.importClass('android.provider.Settings')
        var Uri = plus.android.importClass('android.net.Uri')
        var mainActivity = plus.android.runtimeMainActivity()
        var intent = new Intent()
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        var uri = Uri.fromParts('package', mainActivity.getPackageName(), null)
        intent.setData(uri)
        mainActivity.startActivity(intent)
    }
}

function goTo(url) {
    uni.navigateTo({
        url: url
    })
}

function previewImage(urls, url) {
    if (urls && urls.length > 0)
        uni.previewImage({
            current: url ? url : urls[0],
            urls: urls,
        })
}

import config from '@/utils/config'
// 加密解密
import { encrypt, decrypt } from '@/utils/encrypt.js'

function uploadFile(url, tempFilePath) {//上传图片
    let openid = uni.getStorageSync('openid') || null
    var uploadUrl = config.ApiUrl + config.subDomain + url;

    const currentDate = new Date()
    const month = currentDate.getMonth() + 1
    const datetime = `${currentDate.getFullYear()}-${month.toString().padStart(2, '0')}-${currentDate.getDate().toString().padStart(2, '0')} ${currentDate.getHours().toString().padStart(2, '0')}:${currentDate.getMinutes().toString().padStart(2, '0')}:${currentDate.getSeconds().toString().padStart(2, '0')}`
    const encryptedDateTime = encrypt(datetime)

    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: uploadUrl,
            filePath: tempFilePath,
            header: { 'openid': openid, "Ok": encryptedDateTime },
            name: 'file',
            formData: {
            },
            success(res) {
                resolve(JSON.parse(res.data))
            },
            fail(error) {
                reject(error)
            },
            complete(aaa) {
                // 加载完成
            }
        })
    })
}


function formatNumber(number) {
    let lang = uni.getStorageSync('lang') || 'ug'
    // 检查输入是否有效
    if (typeof number !== 'number' && typeof number !== 'string') {
        return ''
    }

    // 将输入转换为字符串
    let numStr = number.toString()

    // 如果数字包含小数点，只取整数部分
    if (numStr.includes('.')) {
        numStr = numStr.split('.')[0]
    }

    const length = numStr.length
    const num = parseInt(numStr)

    // 中文数字格式化
    if (lang === 'zh') {
        if (length > 8) {
            // 亿以上
            const yi = Math.floor(num / 100000000)
            const wan = Math.floor((num % 100000000) / 10000)
            const remainder = num % 10000

            let result = `${yi}亿`
            if (wan > 0) {
                result += `${wan}万`
            }
            if (remainder > 0) {
                result += `${remainder}`
            }
            return result
        } else if (length > 4) {
            // 万以上
            const wan = Math.floor(num / 10000)
            const remainder = num % 10000

            let result = `${wan}万`
            if (remainder > 0) {
                result += `${remainder}元`
            }
            return result
        }
        return numStr
    }

    // 维吾尔语数字格式化
    if (length > 9) {
        // 十亿以上
        const billions = Math.floor(num / 1000000000)
        const millions = Math.floor((num % 1000000000) / 1000000)
        const thousands = Math.floor((num % 1000000) / 1000)
        const remainder = num % 1000

        let result = `${billions}مىليارد`
        if (millions > 0) {
            result += ` ${millions}مىليون`
        }
        if (thousands > 0) {
            result += ` ${thousands}مىڭ`
        }
        if (remainder > 0) {
            result += ` ${remainder}`
        }
        return result
    } else if (length > 6) {

        // 百万以上
        const millions = Math.floor(num / 1000000)
        const thousands = Math.floor((num % 1000000) / 1000)
        const remainder = num % 1000

        let result = `${millions}مىليون`
        if (thousands > 0) {
            result += ` ${thousands}مىڭ`
        }
        if (remainder > 0) {
            result += ` ${remainder}`
        }
        return result
    } else if (length > 3) {
        // 千以上
        const thousands = Math.floor(num / 1000)
        const remainder = num % 1000

        let result = `${thousands}مىڭ`
        if (remainder > 0) {
            result += ` ${remainder} يۈەن`
        }
        return result
    }

    return numStr
}

const system = uni.getSystemInfoSync()

export default {
    strDir,
    isUyghur,
    isChinese,
    gotoAppPermissionSetting,
    goTo,
    previewImage,
    uploadFile,
    system,
    version: system.appVersion,
    appVersionCode: system.appVersionCode,
    platform: system.platform,
    isIos: system.platform == 'ios',
    formatNumber
}